package com.whfc.mach.xxl.job;

import com.whfc.XxlJobConfig;
import com.whfc.mach.dao.AppMachDataMapper;
import com.whfc.mach.manager.MachDataManager;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Description 设备在线状态任务
 * @Author hw
 * @Date 2021-09-06 9:38
 * @Version 1.0
 */
@Component
@ConditionalOnBean(XxlJobConfig.class)
public class DeviceNetStateCheckJob {

    @Autowired
    private AppMachDataMapper appMachDataMapper;

    @Autowired
    private MachDataManager machDataManager;

    /**
     * 每分钟运行一次
     * (1)处于静止,怠机,运动,计算错误等状态下的硬件,超过3分钟未上传数据,判定为离线.
     * (2)处于休眠状态下的硬件,超过1小时未上传数据,判定为离线.
     */
    @XxlJob("refreshMachDeviceNetState")
    public void refreshMachDeviceNetState() {
        try {
            XxlJobHelper.log("设备刷新设备硬件在线状态服务");
            Date time = new Date();
            List<Integer> machIds = appMachDataMapper.selectNetState2OfflineMachList();
            int count = appMachDataMapper.batchUpdateNetStateOffline(machIds);
            for (Integer machId : machIds) {
                // 增加离线数据点
                try {
                    machDataManager.addOfflineData(machId, time);

                } catch (Exception e) {
                    XxlJobHelper.handleFail("添加离线数据点出错,machId:" + machId + ", error:" + e.getMessage());
                    continue;
                }
            }

            XxlJobHelper.log("本次设备离线数量:{}", count);
        } catch (Exception ex) {
            XxlJobHelper.handleFail("刷新设备在线状态任务,出现异常 error:" + ex.getMessage());
        }
    }
}
